package com.itydl.a03;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.itydl.a03.adapter.MyAdapter;
import com.itydl.a03.domain.Person;
import com.itydl.a03.view.FastIndexView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "FastIndexView";

    private FastIndexView mIndexView;

    //数据源
    List<Person> mPersonList = new ArrayList<>();
    private ListView mListView;
    private TextView mTvShow;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mIndexView = (FastIndexView) findViewById(R.id.indexview);
        mListView = (ListView) findViewById(R.id.lv);
        mTvShow = (TextView) findViewById(R.id.tv_showletter);

        for (int i = 0; i < Strings.NAMES.length; i++) {
        	Person person = new Person(Strings.NAMES[i]);
            mPersonList.add(person);
        }

        //对集合排序
        Collections.sort(mPersonList);

        mIndexView.setOnIndexSelectedListener(new FastIndexView.OnFastIndexSelectedListener() {
            @Override
            public void selected(int position, String letter) {

                showLetter(letter);

                for (int i = 0; i < mPersonList.size(); i++) {
                    String currentLetter = mPersonList.get(i).getPinyin().charAt(0) + "";
                    if(TextUtils.equals(currentLetter,letter)){
                        mListView.setSelection(i);
                        break;
                    }
                }
            }
        });

        mListView.setAdapter(new MyAdapter(mPersonList));
    }

    /**
     * 展示字母
     * @param letter
     */
    private void showLetter(String letter) {
        mTvShow.setText(letter);
        mTvShow.setVisibility(View.VISIBLE);

        //清楚掉之前的延时操作，否则2s即使在滑动索引栏展示文本也会消失
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mTvShow.setVisibility(View.GONE);
            }
        },2000);
    }
}
